package com.yztstudy.Controller;

import com.yztstudy.Entity.AdminUser;
import com.yztstudy.Param.AdminUserParam;
import com.yztstudy.Service.AdminUserService;
import com.yztstudy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * 后台超级管理员登录的表示层
 */

@RestController
public class AdminUserController {

    @Autowired
    private AdminUserService adminUserService;


    /**
     * TODO 用户登录
     * @param adminUserParam 账户+密码+验证码
     * @param result 校验后的结果
     * @param session session域对象
     * @return
     */
    @PostMapping("/user/login")
    public R login(@Validated AdminUserParam adminUserParam, BindingResult result, HttpSession session)
    {
        // TODO 1.如果校验失败
        if (result.hasErrors())
        {
            return R.fail("账号的核心参数为null,无法登录!");
        }

        // TODO 2.验证码校验
        String captcha = (String) session.getAttribute("captcha");
        if (!adminUserParam.getVerCode().equalsIgnoreCase(captcha))
        {
            return R.fail("验证码错误!");
        }

        // TODO 3.账号密码校验
        AdminUser user = adminUserService.login(adminUserParam);
        if (user == null)
        {
            return R.fail("登陆失败!账号或者密码出现错误!");
        }

        // TODO 4.登录成功
        session.setAttribute("userInfo", user);
        return R.ok("登陆成功!");
    }


    /**
     * TODO 退出登录
     * @param session 会话对象
     * @return
     */
    @GetMapping("/user/logout")
    public R logout(HttpSession session)
    {
        // TODO 1.清空session中的数据
        session.invalidate();

        return R.ok("退出登录成功!");
    }
}
